import React, { Component } from "react";
import { BrowserRouter as Router, Route} from "react-router-dom";
import { Layout, Skeleton, Row, Col, Statistic, Table } from "antd";
import { NavBar, Icon, Tabs} from 'antd-mobile';
import { getSchoolTypeNumByEduId, getCountySecurityDataRank} from "../js/api.js";
import moment from 'moment';
import { getCountyComprehensivePointsRankApi, getCountyDangerDealPointsRankApi, getCountyInspectPointsRankApi, getCountyInspectRatesRankApi, getCountyPatrolPointsRankApi, getCountyPatrolRatesRankApi, getEduDangerCategoryApi } from "../js/edudailystatistics.js";
const echarts = require('echarts');

const { Content, Sider } = Layout;

// const WX = require("jweixin-wechat");

class ScoreRankPush extends Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        // getSignature(window.location.href)
        //     .then(res => {
        //         WX.config({
        //             debug: false, //开启debug模式，在验证签名过程中会返回对应信息
        //             appId: res.data.appid,
        //             signature: res.data.signature,
        //             nonceStr: res.data.noncestr,
        //             timestamp: res.data.timestamp,
        //             jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']// 必填，需要使用的JS接口列表
        //         });
        //     })
        //     .catch((e) => {
        //         if (e.response) {
        //             //请求已发出，服务器返回状态码不是2xx。
        //             console.info(e.response.data)
        //             console.info(e.response.status)
        //             console.info(e.response.headers)
        //         } else if (e.request) {
        //             // 请求已发出，但没有收到响应
        //             // e.request 在浏览器里是一个XMLHttpRequest实例，
        //             // 在node中是一个http.ClientRequest实例
        //             console.info(e.request)
        //         } else {
        //             //发送请求时异常，捕捉到错误
        //             console.info('error', e.message)
        //         }
        //         console.info(e.config)
        //     });

        let urlData = this.getUrlParam("state");
        // let urlData = "13,2021-11-08"
        let schoolId = urlData.split(",")[0];
        let date = urlData.split(",")[1];

        // message.info("打印信息====", urlData)
        // WX.ready(function () {
        //     var obj = {
        //         title: date + '巡更情况', // 分享标题
        //         desc: '点击查看' + date + '巡更情况详情！', // 分享描述
        //         link: 'https://tidukeji.cn/dailypush/index.html?state=' + urlData, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        //         // 该链接是重定向链接，因为需要获取用户code，但是该链接又无法直接写微信获取code的链接，
        //         // 所以需要点击后重新加载新的页面，来实现重定向，重新打开获取code的微信链接，实现获取用户信息的功能；
        //         imgUrl: 'https://tidukeji.cn/img/loginIcon.png', // 分享图标
        //         fail: function (res) {
        //             console.log(JSON.stringify(res));
        //         }
        //     };
        //     // 2.1 监听“分享给朋友”，按钮点击、自定义分享内容及分享结果接口
        //     WX.onMenuShareAppMessage(obj);

        //     // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
        //     WX.onMenuShareTimeline(obj);
        // })
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    render() {
        return (
            <Router basename="comprehensiverankpush">
                <Layout style={{ backgroundColor: '#f5f5f5' }}>
                    <Content>
                        <Route path="/" component={ScoreRankpushMain} />
                    </Content>
                </Layout>
            </Router>
        );
    }
}

class ScoreRankpushMain extends Component {
    constructor(props) {
        super(props);
        this.state = {
            confirmLoading: false,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {

        let urlData = this.getUrlParam("state").split(",");
        // let urlData = "1,2021-11-08".split(",")
        let departmentId = urlData[0];
        let data = urlData[1];

        this.setState({
            departmentId: departmentId,
            data: data,
        });

    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    render() {
        const tabs = [
            { title: '综合积分', sub: '0' },
            { title: '区县排名', sub: '1' },
          ];
        return (
            <div>
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                >绍兴全市</NavBar>
                <Tabs tabs={tabs}
                initialPage={0}>
                <div style={{ alignItems: 'center', justifyContent: 'center', height: 'document.documentElement.scrollHeight', backgroundColor: '#fff' }}>
                    <ComprehensiveScore />
                </div>
                <div style={{ alignItems: 'center', justifyContent: 'center', height: 'document.documentElement.scrollHeight', backgroundColor: '#fff' }}>
                    <CountyRank />
                </div>
                </Tabs>
            </div>
        )
    }

}

class ComprehensiveScore extends Component {
    constructor(props) {
        super(props);

        this.state = {
            departmentId: 1,
            confirmLoading: false,
            chartsNum: 3,
            youeryuannum:0,
            xiaoxuenum:0,
            chuzhongnum:0,
            gaozhongnum:0,
            avgchartData: [],
            maxchartData: [],
            categoryChartData: [],
            alldangernum: 0,
            countycomprehensivepointsrank:0,
            countypatrolnumrank:0,
            countypatrolratesrank:0,
            countydangernumrank:0,
            countyinspectratesrank:0,
            countyinspectnumrank:0,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    refreshData() {
        let urlData = this.getUrlParam("state").split(",");
        // let urlData = "1,2021-11-08".split(",")
        let departmentId = urlData[0];
        let data = urlData[1];

        this.setState({
            doneChartsNum: 0,
            departmentId: departmentId,
            data: data,
        });
        
        
        getSchoolTypeNumByEduId(-departmentId)
        .then((res) => {
            this.setState({
                youeryuannum:res.data.youeryuannum,
                xiaoxuenum:res.data.xiaoxuenum,
                chuzhongnum:res.data.chuzhongnum,
                gaozhongnum:res.data.gaozhongnum,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getCountySecurityDataRank(moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'), 1)
        .then((res) => {
            let avgchartData = [];
            let maxchartData = [];
            avgchartData[0] = res.data.avgcountycomprehensivepoints
            avgchartData[1] = res.data.avgcountypatrolpoints
            avgchartData[2] = res.data.avgcountypatrolrates
            avgchartData[3] = res.data.avgcountydangerdealpoints
            avgchartData[4] = res.data.avgcountyinspectrates
            avgchartData[5] = res.data.avgcountyinspectpoints
            maxchartData[0] = res.data.maxcountycomprehensivepoints
            maxchartData[1] = res.data.maxcountypatrolpoints
            maxchartData[2] = res.data.maxcountypatrolrates
            maxchartData[3] = res.data.maxcountydangerdealpoints
            maxchartData[4] = res.data.maxcountyinspectrates
            maxchartData[5] = res.data.maxcountyinspectpoints
            this.setState({
                avgchartData:avgchartData,
                maxchartData:maxchartData,
                alldangernum: res.data.alldangernum,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getEduDangerCategoryApi(-departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
            .then((res) => {
                if (res.data.length == 0) {
                    this.setState({
                        categoryChartData: [],
                        doneChartsNum: this.state.doneChartsNum + 1,
                    });
                } else {
                    let categoryChartData = []
                    res.data.forEach((item, index) => {
                        categoryChartData.push({
                            name: item.category,
                            value: item.num
                        })
                    });
                    this.setState({
                        categoryChartData: categoryChartData,
                        doneChartsNum: this.state.doneChartsNum + 1,
                    });
                }
                console.log('doneChartsNum', this.state.doneChartsNum)
                if (this.state.doneChartsNum == this.state.chartsNum) {
                    this.setState({
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }


    render() {
        return (
            <div>
                <div
                    className='conditionCard'
                    style={{
                        marginTop: '10px',
                        backgroundColor: '#ffffff',
                        padding: '24px',
                    }}>
                        <Skeleton loading={this.state.confirmLoading} active>
                            <Row gutter={[16, 16]} style={{textAlign:'center'}}>
                                <h3>{'数据统计时段:'+ moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD')+'-'+moment().startOf('week').format('YYYY-MM-DD')}</h3>
                            </Row>
                        </Skeleton>
                </div>
                <div
                    className='conditionCard'
                    style={{
                        marginTop: '10px',
                        backgroundColor: '#ffffff',
                        padding: '24px',
                    }}>
                        <Skeleton loading={this.state.confirmLoading} active>
                            <Row gutter={[16, 16]}>
                                <h3>绍兴市学校数量：</h3>
                                <Col span={6} style={{textAlign:'center'}}>
                                    <Statistic title="高中" value={this.state.gaozhongnum} />
                                </Col>
                                <Col span={6} style={{textAlign:'center'}}>
                                    <Statistic title="初中" value={this.state.chuzhongnum} />
                                </Col>
                                <Col span={6} style={{textAlign:'center'}} >
                                    <Statistic title="小学" value={this.state.xiaoxuenum} />
                                </Col>
                                <Col span={6} style={{textAlign:'center'}}>
                                    <Statistic title="幼儿园" value={this.state.youeryuannum} />
                                </Col>
                            </Row>
                        </Skeleton>
                </div>
                <div
                    className='conditionCard'
                    style={{
                    marginTop: '10px',
                    padding: '17.5px',
                    height: 350,
                    backgroundColor: '#ffffff',
                }}>
                    <Skeleton loading={this.state.confirmLoading} active>
                        <h3>安全工作指数雷达图：</h3>
                        <ChartSecurityData
                            that={this}
                            avgchartData={this.state.avgchartData}
                            maxchartData={this.state.maxchartData} />
                    </Skeleton>
                </div>
                <div
                    className='conditionCard'
                    style={{
                        marginTop: '10px',
                        backgroundColor: '#ffffff',
                        padding: '24px',
                    }}>
                        <Skeleton loading={this.state.confirmLoading} active>
                            <Row gutter={[16, 16]}>
                                <h3>详细数值:</h3>
                                <Col span={12} style={{textAlign:'center'}}>
                                    <Statistic title="平均综合积分" value={this.state.avgchartData[0]+'分'} valueStyle={{color:'#00A6FF', fontSize:'14px', marginTop: '16px'}} />
                                </Col>
                                <Col span={12} style={{textAlign:'center'}}>
                                    <Statistic title="隐患积分" value={this.state.avgchartData[3]+'分'} valueStyle={{color:'#00A6FF', fontSize:'14px', marginTop: '16px'}} />
                                </Col>
                                <Col span={12} style={{textAlign:'center'}}>
                                    <Statistic title="平均巡更积分" value={this.state.avgchartData[1]+'分'} valueStyle={{color:'#00A6FF', fontSize:'14px', marginTop: '16px'}} />
                                </Col>
                                <Col span={12} style={{textAlign:'center'}}>
                                    <Statistic title="平均巡更完成率" value={this.state.avgchartData[2]+'%'} valueStyle={{color:'#00A6FF', fontSize:'14px', marginTop: '16px'}} />
                                </Col>
                                <Col span={12} style={{textAlign:'center'}}>
                                    <Statistic title="平均巡检积分" value={this.state.avgchartData[5]+'分'} valueStyle={{color:'#00A6FF', fontSize:'14px', marginTop: '16px'}} />
                                </Col>
                                <Col span={12} style={{textAlign:'center'}}>
                                    <Statistic title="平均巡检完成率" value={this.state.avgchartData[4]+'%'} valueStyle={{color:'#00A6FF', fontSize:'14px', marginTop: '16px'}} />
                                </Col>
                            </Row>
                        </Skeleton>
                </div>
                <div
                    className='conditionCard'
                    style={{
                    marginTop: '10px',
                    padding: '17.5px',
                    height: 350,
                    backgroundColor: '#ffffff',
                }}>
                    <Skeleton loading={this.state.confirmLoading} active>
                        <h3>隐患类型分布图：</h3>
                        <ChartDangerCategory
                            that={this}
                            categoryChartData={this.state.categoryChartData}/>
                    </Skeleton>
                </div>
            </div>
        )
    }
}

class ChartSecurityData extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
            avgchartData:props.avgchartData,
            maxchartData:props.maxchartData,
            that: props.that,
        };
    }

    componentWillReceiveProps(props) {
        this.setState({
            chartData: props.chartData,
            avgchartData:props.avgchartData,
            maxchartData:props.maxchartData,
            that: props.that,
        }, () => {
            this.drawChart();
        })
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {

        let that = this

        let chart = echarts.init(document.getElementById('chartSecurityRank'));
        let option =   {
        tooltip: {
            position: 'inside',
            show: true,
            formatter: function() {
                var html =  '全市 : '+ '<br>'
                            + '综合积分 : ' + that.state.avgchartData[0] + '分<br>'
                            + '巡更积分 : ' + that.state.avgchartData[1] + '分<br>'
                            + '巡更完成率 : ' + that.state.avgchartData[2] + '%<br>'
                            + '隐患积分 : ' + that.state.avgchartData[3] + '分<br>'
                            + '巡检完成率 : ' + that.state.avgchartData[4] + '%<br>'
                            + '巡检积分 : ' + that.state.avgchartData[5] + '分<br>'
                            + '最大 : '+ '<br>'
                            + '综合积分 : ' + that.state.maxchartData[0] + '分<br>'
                            + '巡更积分 : ' + that.state.maxchartData[1] + '分<br>'
                            + '巡更完成率 : ' + that.state.maxchartData[2] + '%<br>'
                            + '隐患积分 : ' + that.state.maxchartData[3] + '分<br>'
                            + '巡检完成率 : ' + that.state.maxchartData[4] + '%<br>'
                            + '巡检积分 : ' + that.state.maxchartData[5] + '分<br>'
                return html
            }
        },
        legend: {
            orient:'horizontal',
            icon: 'circle', //图例形状
            data: ['全市'],
            bottom:'10%',
            right:'center',
            itemWidth: 14, // 图例标记的图形宽度。[ default: 25 ]
            itemHeight: 14, // 图例标记的图形高度。[ default: 14 ]
            itemGap: 21, // 图例每项之间的间隔。[ default: 10 ]横向布局时为水平间隔，纵向布局时为纵向间隔。
            textStyle: {
                fontSize: 14,
            },
        },
        radar: {
            radius: "58%", //大小
            nameGap: 10, // 图中工艺等字距离图的距离
            center: ["50%", "40%"], // 图的位置
            name: {
                textStyle: {
                color: "#333",
                fontSize: 13
                },
            },
            indicator: [
                {"name":'综合积分', "max":this.state.maxchartData[0]},
                {"name":'巡更次数', "max":this.state.maxchartData[1]},
                {"name":'巡更完成率', "max":this.state.maxchartData[2]},
                {"name":'隐患发现数', "max":this.state.maxchartData[3]},
                {"name":'巡检完成率', "max":this.state.maxchartData[4]},
                {"name":'巡检次数', "max":this.state.maxchartData[5]},
            ],
            splitArea: {
                show: true,
                areaStyle: {
                    color: '#fff',
                    shadowColor: 'rgba(14,122,191,0.19)',
                    shadowBlur: 30,
                    shadowOffsetY: 20
                }
            },
            splitLine: {
                show: false,
            },
            axisLine: {
                show: false,
            },
            axisLabel: {
                show: false
            },
        
        },
    
        series: [
            {
                type: "radar",
                data: [
                    {   value:[this.state.maxchartData[0], this.state.maxchartData[1], this.state.maxchartData[2], this.state.maxchartData[3], this.state.maxchartData[4], this.state.maxchartData[5]],
                        symbol: 'none',
                        lineStyle: {
                            width: 0
                        },
                        itemStyle: {
                            color: '#fff'
                        },
                        areaStyle: {
                            color: '#fff',
                            shadowColor: 'rgba(14,122,191,0.15)',
                            shadowBlur: 30,
                            shadowOffsetY: 20
                        }
                    },
                    {   value:[this.state.maxchartData[0]*0.8, this.state.maxchartData[1]*0.8, this.state.maxchartData[2]*0.8, this.state.maxchartData[3]*0.8, this.state.maxchartData[4]*0.8, this.state.maxchartData[5]*0.8],
                        symbol: 'none',
                        lineStyle: {
                            width: 0
                        },
                        itemStyle: {
                            color: '#fff'
                        },
                        areaStyle: {
                            color: '#fff',
                            shadowColor: 'rgba(14,122,191,0.15)',
                            shadowBlur: 30,
                            shadowOffsetY: 20
                        }
                    },
                    {   value:[this.state.maxchartData[0]*0.6, this.state.maxchartData[1]*0.6, this.state.maxchartData[2]*0.6, this.state.maxchartData[3]*0.6, this.state.maxchartData[4]*0.6, this.state.maxchartData[5]*0.6],
                        symbol: 'none',
                        lineStyle: {
                            width: 0
                        },
                        itemStyle: {
                            color: '#fff'
                        },
                        areaStyle: {
                            color: '#fff',
                            shadowColor: 'rgba(14,122,191,0.15)',
                            shadowBlur: 30,
                            shadowOffsetY: 20
                        }
                    },
                    {   value:[this.state.maxchartData[0]*0.4, this.state.maxchartData[1]*0.4, this.state.maxchartData[2]*0.4, this.state.maxchartData[3]*0.4, this.state.maxchartData[4]*0.4, this.state.maxchartData[5]*0.4],
                        symbol: 'none',
                        lineStyle: {
                            width: 0
                        },
                        itemStyle: {
                            color: '#fff'
                        },
                        areaStyle: {
                            color: '#fff',
                            shadowColor: 'rgba(14,122,191,0.15)',
                            shadowBlur: 30,
                            shadowOffsetY: 20
                        }
                    },
                    {   value:[this.state.maxchartData[0]*0.2, this.state.maxchartData[1]*0.2, this.state.maxchartData[2]*0.2, this.state.maxchartData[3]*0.2, this.state.maxchartData[4]*0.2, this.state.maxchartData[5]*0.2],
                        symbol: 'none',
                        lineStyle: {
                            width: 0
                        },
                        itemStyle: {
                            color: '#fff'
                        },
                        areaStyle: {
                            color: '#fff',
                            shadowColor: 'rgba(14,122,191,0.15)',
                            shadowBlur: 30,
                            shadowOffsetY: 20
                        }
                    },
                    {
                        name:'全市',
                        symbol: "circle",
                        symbolSize: 8,
                        value:this.state.avgchartData,
                        areaStyle: {
                            color: "#39B2FF",
                            opacity: 0.3
                        },
                        lineStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: '#00A2FF'
                            }, {
                                offset: 1,
                                color: '#0060FF'
                            }], false),
                            width: 2
                        },
                        itemStyle: {
                            color: "#00DEFF",
                            borderColor: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: '#00DEFF'
                            }, {
                                offset: 1,
                                color: '#1598FF'
                            }], false),
                            borderWidth: 0.5,
                            opacity: 1
                        },
                    },
                    ],
                }
                ]
            }

        chart.setOption(option)
        window.onresize = chart.resize;    
         
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (
        <div id='chartSecurityRank' style={chartStyle} />
        )
    }
}

class ChartDangerCategory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryChartData: props.categoryChartData,
            that: props.that
        };
    }

    componentWillReceiveProps(props) {
        this.setState({
            categoryChartData: props.categoryChartData,
            that: props.that
        }, () => {
            this.drawChart();
        })
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.categoryChartData) != '[]') {
            let chart = echarts.init(document.getElementById('chartSearch'));
            chart.setOption({
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: '70%',  //图例距离左的距离
                    y: 'center',  //图例上下居中
                    itemHeight: 12, // 图例标记的图形高度。[ default: 14 ]
                    itemGap: 8, // 图例每项之间的间隔。[ default: 10 ]横向布局时为水平间隔，纵向布局时为纵向间隔。
                    textStyle: {
                        fontSize: 12,
                    },
                },
                series: [
                    {
                        name: '隐患类别分布',
                        type: 'pie',
                        radius: ['35%', '60%'],
                        center: ['32.5%', '50%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2,
                            normal: {
                                label: {
                                    show:false,
                                    formatter: '{b} : {c} ({d}%)',
                                    textStyle: {
                                        fontSize: 16
                                    },
                                },
                                labelLine: { show: false }
                            }
                        },
                        tooltip: {
                            formatter:  '{b}: {c}个'
                        },
                        data: this.state.categoryChartData
                    }
                ]
            })
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '90%',
            width: '100%',
        };
        return (<div id='chartSearch' style={chartStyle} />)
    }
}

class CountyRank extends Component {
    constructor(props) {
        super(props);

        this.state = {
            departmentId: 1,
            confirmLoading: false,
            chartsNum: 6,
            comprehensivePointsColumnData: [],
            dangerDealPointsColumnData: [],
            inspectPointsColumnData: [],
            inspectRatesColumnData: [],
            patrolPointsColumnData: [],
            patrolRatesColumnData: []
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    refreshData() {
        let urlData = this.getUrlParam("state").split(",");
        // let urlData = "1,2021-11-08".split(",")
        let departmentId = urlData[0];
        let data = urlData[1];

        this.setState({
            doneChartsNum: 0,
            departmentId: departmentId,
            data: data,
        });
        
        
        let comprehensivePointsColumnData = [];
        let dangerDealPointsColumnData = [];
        let inspectPointsColumnData = [];
        let inspectRatesColumnData = [];
        let patrolPointsColumnData = [];
        let patrolRatesColumnData = [];

        getCountyComprehensivePointsRankApi(departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
        .then((res) => {
            res.data.countycomprehensivepointsrankList.forEach((item, index) => {
                comprehensivePointsColumnData.push({
                    key: index + 1,
                    departmentName: item.departmentName,
                    comprehensivepoints: item.comprehensivepoints+'分',
                });
            });

            this.setState({
                comprehensivePointsColumnData: comprehensivePointsColumnData,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getCountyDangerDealPointsRankApi(departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
        .then((res) => {
            res.data.countydangerdealpointsrankList.forEach((item, index) => {
                dangerDealPointsColumnData.push({
                    key: index + 1,
                    departmentName: item.departmentName,
                    dangerdealpoints: item.dangerdealpoints+'分',
                });
            });

            this.setState({
                dangerDealPointsColumnData: dangerDealPointsColumnData,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
        
        getCountyInspectPointsRankApi(departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
        .then((res) => {
            res.data.countyinspectpointsrankList.forEach((item, index) => {
                inspectPointsColumnData.push({
                    key: index + 1,
                    departmentName: item.departmentName,
                    inspectpoints: item.inspectpoints+'分',
                });
            });

            this.setState({
                inspectPointsColumnData: inspectPointsColumnData,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getCountyInspectRatesRankApi(departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
        .then((res) => {
            res.data.countyinspectratesrankList.forEach((item, index) => {
                inspectRatesColumnData.push({
                    key: index + 1,
                    departmentName: item.departmentName,
                    inspectrates: item.inspectrates+'%',
                });
            });

            this.setState({
                inspectRatesColumnData: inspectRatesColumnData,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getCountyPatrolPointsRankApi(departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
        .then((res) => {
            res.data.countypatrolpointsrankList.forEach((item, index) => {
                patrolPointsColumnData.push({
                    key: index + 1,
                    departmentName: item.departmentName,
                    patrolpoints: item.patrolpoints+'分',
                });
            });

            this.setState({
                patrolPointsColumnData: patrolPointsColumnData,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getCountyPatrolRatesRankApi(departmentId, undefined, moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD'), moment().startOf('week').format('YYYY-MM-DD'))
        .then((res) => {
            res.data.countypatrolratesrankList.forEach((item, index) => {
                patrolRatesColumnData.push({
                    key: index + 1,
                    departmentName: item.departmentName,
                    patrolrates: item.patrolrates+'%',
                });
            });

            this.setState({
                patrolRatesColumnData: patrolRatesColumnData,
                doneChartsNum: this.state.doneChartsNum + 1,
            });
            //所有图表数据都加载完成才使骨架屏可见
            console.log('doneChartsNum', this.state.doneChartsNum)
            if (this.state.doneChartsNum == this.state.chartsNum) {
                this.setState({
                    confirmLoading: false,
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

    }


    render() {

        let keyWidth = 60;
        let departmentNameWidth = 150;
        let comprehensivepointsWidth = 90;
        let dangerdealpointsWidth = 90;
        let inspectpointsWidth = 90;
        let inspectratesWidth = 90;
        let patrolpointsWidth = 90;
        let patrolratesWidth = 90;

        const comprehensivepointscolumns = [{
            title: "排名",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "区县名称",
            dataIndex: "departmentName",
            key: "departmentName",
            width: departmentNameWidth,
        }, {
            title: "综合积分",
            dataIndex: "comprehensivepoints",
            key: "comprehensivepoints",
            width: comprehensivepointsWidth,
        }]

        const dangerdealpointscolumns = [{
            title: "排名",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "区县名称",
            dataIndex: "departmentName",
            key: "departmentName",
            width: departmentNameWidth,
        }, {
            title: "隐患积分",
            dataIndex: "dangerdealpoints",
            key: "dangerdealpoints",
            width: dangerdealpointsWidth,
        }]

        const inspectpointscolumns = [{
            title: "排名",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "区县名称",
            dataIndex: "departmentName",
            key: "departmentName",
            width: departmentNameWidth,
        }, {
            title: "巡检积分",
            dataIndex: "inspectpoints",
            key: "inspectpoints",
            width: inspectpointsWidth,
        }]

        const inspectratescolumns = [{
            title: "排名",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "区县名称",
            dataIndex: "departmentName",
            key: "departmentName",
            width: departmentNameWidth,
        }, {
            title: "巡检完成率",
            dataIndex: "inspectrates",
            key: "inspectrates",
            width: inspectratesWidth,
        }]

        const patrolpointscolumns = [{
            title: "排名",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "区县名称",
            dataIndex: "departmentName",
            key: "departmentName",
            width: departmentNameWidth,
        }, {
            title: "巡更积分",
            dataIndex: "patrolpoints",
            key: "patrolpoints",
            width: patrolpointsWidth,
        }]

        const patrolratescolumns = [{
            title: "排名",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "区县名称",
            dataIndex: "departmentName",
            key: "departmentName",
            width: departmentNameWidth,
        }, {
            title: "巡更完成率",
            dataIndex: "patrolrates",
            key: "patrolrates",
            width: patrolratesWidth,
        }]

        return (
            <div>
                <div
                    className='conditionCard'
                    style={{
                        marginTop: '10px',
                        backgroundColor: '#ffffff',
                        padding: '24px',
                    }}>
                        <Skeleton loading={this.state.confirmLoading} active>
                            <Row gutter={[16, 16]} style={{textAlign:'center'}}>
                                <h3>{'数据统计时段:'+ moment().startOf('week').subtract(6, 'days').format('YYYY-MM-DD')+'-'+moment().startOf('week').format('YYYY-MM-DD')}</h3>
                            </Row>
                        </Skeleton>
                </div>
                <div
                className='conditionCard'
                style={{
                    marginTop: '10px',
                    backgroundColor: '#ffffff',
                    padding: '24px',
                }}>
                    <h3 style={{marginBottom:'20px'}}>区县学校平均综合积分排名：</h3>
                    <Table
                    dataSource={this.state.comprehensivePointsColumnData}
                    columns={comprehensivepointscolumns}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={false}
                    size="small"
                    />
                </div>
                <div
                className='conditionCard'
                style={{
                    marginTop: '10px',
                    backgroundColor: '#ffffff',
                    padding: '24px',
                }}>
                    <h3 style={{marginBottom:'20px'}}>区县总隐患积分排名：</h3>
                    <Table
                    dataSource={this.state.dangerDealPointsColumnData}
                    columns={dangerdealpointscolumns}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={false}
                    size="small"
                    />
                </div>
                <div
                className='conditionCard'
                style={{
                    marginTop: '10px',
                    backgroundColor: '#ffffff',
                    padding: '24px',
                }}>
                    <h3 style={{marginBottom:'20px'}}>区县学校平均巡更积分排名：</h3>
                    <Table
                    dataSource={this.state.patrolPointsColumnData}
                    columns={patrolpointscolumns}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={false}
                    size="small"
                    />
                </div>
                <div
                className='conditionCard'
                style={{
                    marginTop: '10px',
                    backgroundColor: '#ffffff',
                    padding: '24px',
                }}>
                    <h3 style={{marginBottom:'20px'}}>区县学校平均巡更完成率排名：</h3>
                    <Table
                    dataSource={this.state.patrolRatesColumnData}
                    columns={patrolratescolumns}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={false}
                    size="small"
                    />
                </div>
                <div
                className='conditionCard'
                style={{
                    marginTop: '10px',
                    backgroundColor: '#ffffff',
                    padding: '24px',
                }}>
                    <h3 style={{marginBottom:'20px'}}>区县学校平均巡检积分排名：</h3>
                    <Table
                    dataSource={this.state.inspectPointsColumnData}
                    columns={inspectpointscolumns}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={false}
                    size="small"
                    />
                </div>
                <div
                className='conditionCard'
                style={{
                    marginTop: '10px',
                    backgroundColor: '#ffffff',
                    padding: '24px',
                }}>
                    <h3 style={{marginBottom:'20px'}}>区县学校平均巡检完成率排名：</h3>
                    <Table
                    dataSource={this.state.inspectRatesColumnData}
                    columns={inspectratescolumns}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={false}
                    size="small"
                    />
                </div>
            </div>
        )
    }
}

export default ScoreRankPush;